import { useState, useEffect } from "react";
import {
  NavBar,
  Icon,
  InputItem,
  WingBlank,
  WhiteSpace,
  Button,
  Toast,
} from "antd-mobile";
import { Link } from "react-router-dom";

import { reqSendCode } from "../../../api/register";
import { reqLoginPhone } from "../../../api/login";
import { phoneReg, codeReg } from "../../../utils/regs";

import "./index.less";

const MAX_TIME = 5;

function Login({ history, location }) {
  // 手机号
  const [phone, setPhone] = useState("");
  const [code, setCode] = useState("");
  // 决定是否可以发送验证码（发送验证码按钮是否禁用）
  const [isCodeDisabled, setIsCodeDisabled] = useState(true);
  const [isBtnDisabled, setIsBtnDisabled] = useState(true);
  // 是否发送过验证码
  const [isSendCode, setIsSendCode] = useState(false);
  const [time, setTime] = useState(0);

  // 处理手机号change事件回调
  const phoneInputChange = (val) => {
    if (phoneReg.test(val)) {
      setIsCodeDisabled(false);
    } else {
      setIsCodeDisabled(true);
    }
    setPhone(val);
  };

  const codeInputChange = (val) => {
    if (codeReg.test(val)) {
      setIsBtnDisabled(false);
    } else {
      setIsBtnDisabled(true);
    }
    setCode(val);
  };

  // 点击发送验证码
  const sendCode = () => {
    // 解决touch事件再disbled不会禁用问题
    if (isCodeDisabled) return;

    setIsSendCode(true);
    // 倒计时效果
    setTime(MAX_TIME);
    // 发送请求，验证码
    reqSendCode(phone);
  };

  useEffect(() => {
    // 初始化渲染不要进来
    if (time === 0) {
      return;
    }
    setTimeout(() => {
      if (time === 1) {
        setIsSendCode(false);
        return;
      }
      setTime(time - 1);
    }, 1000);
  }, [time]);

  const login = async () => {
    const res = await reqLoginPhone(phone, code);
    if (res.data.code === 20000) {
      // console.log(res);
      history.push("/", res.data.data);
    } else {
      Toast.fail(res.data.message, 2);
    }
  };

  const goCountry = () => {
    history.push("/countryPicker", "/login/code");
  };

  const goGitee = () => {
    window.location.href =
      "https://gitee.com/oauth/authorize?client_id=30d8924469fade7a7c27bb572e1fd571a9070c64b6a350511aadedf1bb3870cd&redirect_uri=http://localhost:5000/login/oauth/gitee&response_type=code";
  };

  const prefix = location.state || "86";

  return (
    <div className="login container">
      <NavBar mode="light">硅谷注册登录</NavBar>
      <WhiteSpace size="xl" />
      <WingBlank size="lg">
        <InputItem
          clear
          placeholder="请输入手机号"
          className="input-item"
          value={phone}
          onChange={phoneInputChange}>
          <span className="phone-prefix" onTouchEnd={goCountry}>
            <span>+{prefix}</span>
            <Icon type="down" />
          </span>
        </InputItem>
        <WhiteSpace size="lg" />
        <div className="login-code">
          <InputItem
            clear
            placeholder="请输入手机验证码"
            className="input-item"
            value={code}
            onChange={codeInputChange}
          />
          {isSendCode ? (
            <button
              className="login-btn-text login-btn"
              style={{
                color: "#848689",
              }}>
              重新获取({time}s)
            </button>
          ) : (
            <button
              className="login-btn-text login-btn"
              style={{
                color: isCodeDisabled ? "#848689" : "red",
              }}
              onTouchEnd={sendCode}>
              获取验证码
            </button>
          )}
        </div>
        <WhiteSpace size="lg" />
        <WingBlank size="lg">
          <Button
            disabled={isBtnDisabled || isCodeDisabled}
            type="primary"
            className="btn"
            onClick={login}>
            登录
          </Button>
        </WingBlank>
        <WhiteSpace size="lg" />
        <div className="login-btn-wrap">
          <Link to="/login/password" className="login-btn-text">
            账户密码登录
          </Link>
          <Link to="/register/phone" className="login-btn-text">
            手机快速注册
          </Link>
        </div>
        <div className="login-other-text">其他登录方式</div>
        <div className="login-icons">
          {/* https://gitee.com/api/v5/oauth_doc#/ */}

          <span
            className="iconfont icon-gitee-fill-round"
            onTouchEnd={goGitee}></span>

          <span className="iconfont icon-qq"></span>
          <span className="iconfont icon-weixin"></span>
        </div>
        <span className="login-private-policy">
          未注册的手机号验证后将自动创建硅谷账号, 登录即代表您已同意
          <a className="login-private-policy-btn">硅谷隐私政策</a>
        </span>
      </WingBlank>
    </div>
  );
}

export default Login;
